import { createAction } from 'redux-actions';
import * as types from '../constants/ActionTypes';
import * as Api from '../utils/WebAPIUtils.js';
import Tool from '../utils/ToolUtils.js';
import FileUploadTool from '../utils/FileUploadAPIUtils.js';

const fetchTestPackage = createAction(types.FETCH_TEST_PACKAGE, testPackageList => testPackageList);
const getTestPackage = createAction(types.GET_ONE_TEST_PACKAGE, onetestPackage => onetestPackage);
// const saveTestPackage = createAction(types.SAVE_TEST_PACKAGE, testPackage => testPackage);
const saveErrorMsg = createAction(types.SAVE_TEST_PACKAGE_ERROR_MSG, testPackageErrorMsg => testPackageErrorMsg);
const uploadErrorMsg = createAction(types.UPLOAD_ERROR_MSG, data => data);
const uploadTestPackage = createAction(types.UPLOAD_TEST_PACKAGE, packageData => packageData);
const uploadProgress = createAction(types.UPLOAD_PROPRESS, ProgressData => ProgressData);
const resetUploadProgress = createAction(types.RESET_UPLOAD_PROPRESS, data => data);
const cancelUpload = createAction(types.CANCEL_UPLOAD, data => data);
exports.restoreTestPackage = createAction(types.RESTORE_TEST_PACKAGE, data => data);
exports.resetUploadErrorMsg = createAction(types.RESET_UPLOAD_ERROR_MSG, data => data);
exports.resetUploadData = createAction(types.RESET_UPLOAD_DATA, data => data);
// 取消上传
// ========
exports.cancelUpload = (data) => (dispath) =>
  dispath(cancelUpload(data));
// 获取所有测试池数据
// ==================
exports.fetchTestPackage = (data) => (dispath, getStates) =>
  Tool.post(Api.tesPackage.query, data, (res) => {
    dispath(fetchTestPackage(res));
  });

// 获取单条测试包信息
// ==================
exports.getOneTestPackage = (data) => (dispath, getStates) =>
  Tool.post(Api.tesPackage.get, data, (res) => {
    console.log('res', res)
    if (res.code === 200) {
      dispath(getTestPackage(res.data));
    }
  });
// 编辑测试包信息
// ==================
exports.editTestPackage = (data, router) => (dispath) =>
  Tool.post(Api.tesPackage.edit, data, (res) => {
    if (res.code === 200) {
      router.push('/');
    } else if (res.code === 90001 || res.code === 90003) {
      dispath(saveErrorMsg(res.data));
    }
  });
// 新增测试包信息
// ==================
exports.saveTestPackage = (data, router) => (dispath) =>
  Tool.post(Api.tesPackage.new, data, (res) => {
    if (res.code === 200) {
      router.push('/');
    } else if (res.code === 90001 || res.code === 90003) {
      dispath(saveErrorMsg(res.data));
    }
  }, (error) => { console.log('error'); });
// 上传测试包
// ==================
exports.uploadFile = (data) => (dispath) => {
  FileUploadTool.post(
    Api.uploadFile, data,
    (res) => {
      if (res.code === 200) {
        dispath(uploadTestPackage(res.data));
        dispath(uploadErrorMsg(res));
        dispath(resetUploadProgress());
      } else {
        dispath(uploadErrorMsg(res));
      }
    },
    (ProgressData) => {
      dispath(uploadProgress(ProgressData));
    },
    (error) => {}
  );
};
